import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'dart:async';

/// 性能优化工具类
class PerformanceUtils {
  /// 防抖函数，用于减少频繁调用
  static Function debounce(Function fn, {Duration duration = const Duration(milliseconds: 300)}) {
    Timer? timer;
    return () {
      if (timer != null) {
        timer!.cancel();
      }
      timer = Timer(duration, () {
        fn();
      });
    };
  }
  
  /// 节流函数，用于限制函数调用频率
  static Function throttle(Function fn, {Duration duration = const Duration(milliseconds: 300)}) {
    bool canRun = true;
    return () {
      if (canRun) {
        canRun = false;
        fn();
        Future.delayed(duration, () {
          canRun = true;
        });
      }
    };
  }
  
  /// 在下一帧执行，避免在同一帧内进行多次布局计算
  static void runOnNextFrame(VoidCallback callback) {
    SchedulerBinding.instance.addPostFrameCallback((_) {
      callback();
    });
  }
  
  /// 图片预加载
  static Future<void> preloadImages(BuildContext context, List<String> assetPaths) async {
    for (final path in assetPaths) {
      precacheImage(AssetImage(path), context);
    }
  }
  
  /// 延迟加载组件
  static Widget delayedWidget({
    required Widget child,
    Duration delay = const Duration(milliseconds: 100),
    Widget placeholder = const SizedBox(),
  }) {
    return FutureBuilder(
      future: Future.delayed(delay),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return child;
        }
        return placeholder;
      },
    );
  }
} 